package com.weizhong.update.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class NetworkUtil {

	public static NetworkInfo[] getAllNetworkInfo(ConnectivityManager con) {
		NetworkInfo[] networkInfos = con.getAllNetworkInfo();
		return networkInfos;
	}

	/**
	 * 检查网络信息
	 */
	public static void checkNetworkInfo(Context context,
			ConnectivityManager conMan) {

		NetworkInfo[] networkInfos = conMan.getAllNetworkInfo();
		for (int i = 0; i < networkInfos.length; i++) {
			System.out.println("type:" + networkInfos[i].getType() + ";"
					+ networkInfos[i].getExtraInfo());
			System.out.println("type:" + networkInfos[i].getState() + ";"
					+ networkInfos[i].getTypeName() + ";"
					+ networkInfos[i].getSubtypeName());
		}
		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		System.out.println("mobile:" + mobile);
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		System.out.println("wifi:"
				+ wifi
				+ ";"
				+ conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
						.getTypeName()
				+ ";"
				+ conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
						.getSubtypeName());

		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return;
	}

	/**
	 * 获得ip地址
	 * 
	 * @return
	 */
	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return "本地ip地址：" + inetAddress.getCanonicalHostName()
								+ "子网掩码:" + "默认网关:" + "DNS:"
								+ inetAddress.getHostName() + ";"
								+ inetAddress.getHostAddress();
						// return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("test", ex.toString());
		}
		return null;
	}

	/**
	 * 有线网mac地址 未实验
	 */
	public static void getMac() {
		// Physical Address. . . . . . . . . :
		InputStream input = null;
		try {
			// 执行命令
			ProcessBuilder builder = new ProcessBuilder("ipconfig ", "/all ");
			Process process = builder.start();
			input = process.getInputStream();

			// 把得到的流得到
			byte[] b = new byte[1024];
			StringBuffer buffer = new StringBuffer();
			while (input.read(b) > 0) {
				buffer.append(new String(b));
			}

			// 分析流
			String value = buffer.substring(0);
			String systemFlag = "Physical   Address.   .   .   .   .   .   .   .   .   : ";
			int index = value.indexOf(systemFlag);
			List<String> address = new ArrayList<String>();
			if (0 < index) {
				value = buffer.substring(index + systemFlag.length());
				address.add(value.substring(0, 18));
			}

			// 打印输出
			for (String add : address) {
				System.out.println(add);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				input.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void getMac2(Context context) {
		// 在wifi未开启状态下，仍然可以获取MAC地址，但是IP地址必须在已连接状态下否则为0
		String macAddress = null, ip = null;
		WifiManager wifiMgr = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
		if (null != info) {
			macAddress = info.getMacAddress();
			// ip = int2ip(info.getIpAddress()); //ip地址转换
		}
		System.out.println("mac:" + macAddress + ",ip:" + ip);
	}

	/**
	 * 检查网络是否可用
	 * 
	 * @param manager
	 * @return
	 */
	public static boolean isNetworkAvaiable(Context context) {		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);		if (manager == null) {			return false;		}		NetworkInfo networkinfo = manager.getActiveNetworkInfo();		if (networkinfo == null ) {			return false;		}		// 通过连接状态判断是否可连		if (networkinfo.getState().equals(NetworkInfo.State.CONNECTED)) {			return true;		} else if (networkinfo.getState().equals(NetworkInfo.State.DISCONNECTED)) {			return false;		}		return false;	}
	/**	 * 是否以太网连接	 * @param context	 * @return	 */	public static boolean isEthAvaiable(Context context) {		ConnectivityManager manager = (ConnectivityManager) context				.getSystemService(Context.CONNECTIVITY_SERVICE);		if (manager == null) {			return false;		}
		NetworkInfo networkinfo = manager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);		if (networkinfo == null ) {			return false;		}
		// 通过连接状态判断是否可连		if(networkinfo.isConnected())			return true;		return false;	}
	

	/**
	 * 通过ping方法 address 网络地址,检查路由器可用 192.168.1.1 wlan:http://www.baidu.com
	 */
	public static boolean isNetworkAvaiable2(String address) {
		try {
			Process process = Runtime.getRuntime().exec("ping " + address);
			InputStreamReader r = new InputStreamReader(
					process.getInputStream());
			LineNumberReader returnData = new LineNumberReader(r);

			String returnMsg = "";
			String line = "";

			while ((line = returnData.readLine()) != null) {
				System.out.println(line);
				returnMsg += line;
			}
			// 判断结果中是否有100% loss 有则不连通
			if (returnMsg.indexOf("100% loss") != -1) {
				System.out.println("与 " + address + " 连接不畅通.");
				return false;
			} else {
				System.out.println("与 " + address + " 连接畅通.");
				return true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 检查网络是否可用通过url方式
	 * 
	 * @param netFileUrl
	 *            网络url
	 * @return
	 */
	public static boolean isNetworkAvaiable(String netFileUrl) {
		try {
			URL url = new URL(netFileUrl);
			URLConnection urlConn = url.openConnection();
			InputStream netFileInputStream = urlConn.getInputStream();
			if (null != netFileInputStream) {
				return true;
			} else {
				return false;
			}
		} catch (IOException e) {
			return false;
		}
	}
	
	/**
	 * 返回wifi ap是否可用
	 * @return
	 *//*
	public static boolean isWifiApAliable(Context context){
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		
	}*/
}
